package com.taotao.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.ExceptionUtil;
import com.taotao.common.utils.IDUtils;
import com.taotao.dao.ItemDescMapper;
import com.taotao.dao.ItemMapper;
import com.taotao.dto.EasyUIResult;
import com.taotao.model.Item;
import com.taotao.model.ItemDesc;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Date;

/**
 * ItemServiceImpl
 * Created by heqianqian on 2017/7/5.
 */
@Service
public class ItemServiceImpl implements ItemService {

    @Resource
    private ItemMapper itemMapper;

    @Resource
    private ItemDescMapper itemDescMapper;

    @Override
    public Item findItemById(Long id) {
        return itemMapper.selectByPrimaryKey(id);
    }

    @Override
    public EasyUIResult<List<Item>> listItem(Integer page, Integer rows) {
        PageHelper.startPage(page, rows);
        List<Item> items = itemMapper.listItems();
        Page<Item> itemsPage = (Page<Item>) items;
        long total = itemsPage.getTotal();
        return new EasyUIResult<>((int) total, items);
    }

    @Override
    public TaotaoResult addItem(Item item, ItemDesc itemDesc) {
        try {
            //获取id主键
            long itemId = IDUtils.genItemId();
            Date date = new Date();
            //添加商品信息
            item.setId(itemId);
            item.setStatus((byte) 1);
            item.setUpdated(date);
            item.setCreated(date);
            itemMapper.insert(item);
            //添加商品描述信息
            itemDesc.setItemId(itemId);
            itemDesc.setCreated(date);
            itemDesc.setUpdated(date);
            itemDescMapper.insert(itemDesc);
        } catch (Exception e) {
            return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
        }
        return TaotaoResult.ok();
    }

    @Override
    @Transactional
    public TaotaoResult deleteItem(long[] ids) {
        for (int i = 0; i < ids.length; i++) {
            int result = itemMapper.deleteByPrimaryKey(ids[i]);
            if (result <= 0) {
                return TaotaoResult.build(0, "删除失败");
            }
        }
        return TaotaoResult.ok();
    }
}
